#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"

@implementation AppDelegate

const static long long TIME_OUT_NS = 15 * NSEC_PER_SEC;//15 seconds
static FlutterEventSink flutterEventSink;
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    @try {
        self.flutterEngine = [[FlutterEngine alloc] initWithName:@"myFlutterEngine"];
        // Runs the default Dart entrypoint with a default Flutter route.
        [self.flutterEngine run];
        // Used to connect plugins (only if you have plugins with iOS platform code).
        [GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
        
        [XMReqMgr sharedInstance].delegate = self;
        [[XMReqMgr sharedInstance] registerXMReqInfoWithKey:@"840c5ccc5d8231dcec880a274e352b0d" appSecret:@"639fb0db487124649ded0aa63df25d9b"];
        [NSThread sleepForTimeInterval:1.5];
        
        FlutterEngine *flutterEngine = ((AppDelegate *)UIApplication.sharedApplication.delegate).flutterEngine;
        FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
        self.window.rootViewController = flutterViewController;
        
        [self registerMethodChannel:flutterEngine];
        [self registerMethonEvent:flutterEngine];
    } @catch (NSException *exception) {
        NSLog(@"Exception: %@", exception);
        UIAlertView * alert =[[UIAlertView alloc]initWithTitle:@"错误" message: [[NSString alloc] initWithFormat:@"%@",exception] delegate:self cancelButtonTitle:nil
         otherButtonTitles:@"OK", nil];
        [alert show];
    } @finally {
        
    }
    
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)applicationWillTerminate:(UIApplication *)application{
    [[XMReqMgr sharedInstance] closeXMReqMgr];
}

- (int)getBatteryLevel {
    UIDevice* device = UIDevice.currentDevice;
    device.batteryMonitoringEnabled = YES;
    if (device.batteryState == UIDeviceBatteryStateUnknown) {
        return -1;
    } else {
        return (int)(device.batteryLevel * 100);
    }
}
- (void)didXMInitReqOK:(BOOL)result{
    NSLog(@"didXMInitReqOK %@", result?@"true":@"fasle");
}
- (void)didXMInitReqFail:(XMErrorModel *)respModel {
    NSLog(@"didXMInitReqFail");
}

- (void)registerMethonEvent:(FlutterEngine *)flutterEngine{
    FlutterEventChannel *channel = [FlutterEventChannel eventChannelWithName:@"dar.flutter.io/event_channel" binaryMessenger:flutterEngine.binaryMessenger];
    [channel setStreamHandler:self];
}

- (void)registerMethodChannel:(FlutterEngine *)flutterEngine{
    [[XMSDKPlayer sharedPlayer] setAutoNexTrack:YES];
    [[XMSDKPlayer sharedPlayer] setPlayMode:XMSDKPlayModeTrack];
    [XMSDKPlayer sharedPlayer].trackPlayDelegate = self;
    FlutterMethodChannel *channel = [FlutterMethodChannel
                                            methodChannelWithName:@"dar.flutter.io/method_channel"
                                            binaryMessenger:flutterEngine.binaryMessenger];
    [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        NSLog(@"ios-----call.method: %@  arguments: %@", call.method, call.arguments);
        if ([@"getBatteryLevel" isEqualToString:call.method]) {
            int batteryLevel = [self getBatteryLevel];
            if (batteryLevel == -1) {
                result([FlutterError errorWithCode:@"UNAVAILABLE"
                                           message:@"Battery info unavailable"
                                           details:nil]);
            } else {
                result(@(batteryLevel));
            }
        } else if ([@"getAlbumJsonInfo" isEqualToString:call.method]){
            NSString *platformbid = call.arguments[@"platformbid"];
            NSString *platform = call.arguments[@"platform"];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:platformbid forKey:@"ids"];
            FlutterResult res = result;
            [[XMReqMgr sharedInstance] requestXMData:XMReqType_AlbumsBatch params:params
                                withCompletionHander:^(id result, XMErrorModel *error){
                                    NSLog(@"getAlbumJsonInfo--result:%@  error:%@", result, error);
                                    if(!error){
                                        if([result isKindOfClass:[NSArray class]]){
                                            for (NSDictionary *dic in result) {
                                                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
                                                NSString *resultString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                                                res(resultString);
                                                break;
                                            }
                                        }
                                    } else {
                                        res(error.description);
                                    }
                                }];

        } else if ([@"getChaptersJsonInfo" isEqualToString:call.method]){
            NSString *platformbid = call.arguments[@"platformbid"];
            NSString *platform = call.arguments[@"platform"];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:platformbid forKey:@"album_id"];
            [params setObject:call.arguments[@"pageSize"] forKey:@"count"];
            [params setObject:call.arguments[@"page"] forKey:@"page"];
            FlutterResult res = result;
            [[XMReqMgr sharedInstance]    requestXMData:XMReqType_AlbumsBrowse params:params
                                   withCompletionHander:^(id result, XMErrorModel *error)    {
//                                       NSLog(@"getChaptersJsonInfo--result:%@  error:%@", result, error);
                                       if(!error){
                                           if([result isKindOfClass:[NSDictionary class]]){
                                               NSDictionary * dic = result;
                                               id tracks = [dic objectForKey:@"tracks"];
//                                               NSLog(@"tracks---:%@", tracks);
                                               NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tracks options:NSJSONWritingPrettyPrinted error:nil];
                                               NSString *resultString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                                               res(resultString);
                                               res(tracks);
                                           }
                                       } else {
                                           res(error.description);
                                       }
                                   }];
        } else if ([@"playList" isEqualToString:call.method]){
            NSString *channelListJson = call.arguments[@"listData"];
            NSString *platform = call.arguments[@"platform"];
            BOOL playNow = call.arguments[@"playNow"];
            NSData *jsonData = [channelListJson dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *tracks = [NSMutableArray array];
            int i=0;
            for (NSDictionary *d in [dic objectForKey:@"list"]) {
                XMTrack *track = [[XMTrack alloc] init];
                track.kind = @"track";
                track.trackTitle = [d objectForKey:@"trackTitle"];
                track.trackIntro = [d objectForKey:@"trackIntro"];
                track.trackId = [[d objectForKey:@"dataId"] integerValue];
                track.coverUrlMiddle = [d objectForKey:@"pic"];
                track.duration = [[d objectForKey:@"duration"] integerValue];
                if([d objectForKey:@"playUrl32"]){
                    track.playUrl32 = [d objectForKey:@"playUrl32"];
                }
                [tracks addObject:track];
                i++;
            }
//            saveNowPlayBookName(playList.bookName);
            if ([dic objectForKey:@"playModel"] == 0) {
                [[XMSDKPlayer sharedPlayer] setTrackPlayMode:XMTrackModeCycle];
            } else {
                [[XMSDKPlayer sharedPlayer] setTrackPlayMode:XMTrackModeSingle];
            }
//            Class dataClass = NSClassFromString(@"XMTrack");
//            id nowTrack = [[dataClass alloc] initWithDictionary:dic];
            NSInteger index = [[dic objectForKey:@"index"] integerValue];
            [[XMSDKPlayer sharedPlayer] playWithTrack:tracks[index] playlist:tracks];
            if (playNow) {

            } else {
                [[XMSDKPlayer sharedPlayer] pauseTrackPlay];
            }
            result(@(true));
        } else if ([@"playerPause" isEqualToString:call.method]){
            NSString *platform = call.arguments[@"platform"];
            [[XMSDKPlayer sharedPlayer] pauseTrackPlay];
            result(@(true));
        } else if ([@"playerPlay" isEqualToString:call.method]){
            NSString *platform = call.arguments[@"platform"];
            [[XMSDKPlayer sharedPlayer] resumeTrackPlay];
            result(@(true));
        } else if ([@"playerNext" isEqualToString:call.method]){
            NSString *platform = call.arguments[@"platform"];
            [[XMSDKPlayer sharedPlayer] playNextTrack];
            result(@(true));
        } else if ([@"playerPrev" isEqualToString:call.method]){
            NSString *platform = call.arguments[@"platform"];
            [[XMSDKPlayer sharedPlayer] playPrevTrack];
            result(@(true));
        } else if ([@"setPlayModel" isEqualToString:call.method]){
            NSString *platform = call.arguments[@"platform"];
            if (call.arguments[@"model"] == 0) {
                [[XMSDKPlayer sharedPlayer] setTrackPlayMode:XMTrackModeCycle];
            } else {
                [[XMSDKPlayer sharedPlayer] setTrackPlayMode:XMTrackModeSingle];
            }
            result(@(true));
        } else if ([@"getNowPlayList" isEqualToString:call.method]){
            NSString *platform = call.arguments[@"platform"];
            result(@"{}");
        } else if ([@"seekToByPercent" isEqualToString:call.method]){
            NSString *platform = call.arguments[@"platform"];
            NSLog(@"percent=%@", call.arguments[@"percent"]);
            NSLog(@"all=%@", call.arguments[@"all"]);
            CGFloat time = [call.arguments[@"percent"] floatValue] * [call.arguments[@"all"] integerValue];
            [[XMSDKPlayer sharedPlayer] seekToTime:time];
            result(@(true));
        }else {
            NSLog(@"ios--FlutterMethodNotImplemented");
            result(FlutterMethodNotImplemented);
        }
    }];
}

- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events{
    NSLog(@"ios--onListenWithArguments: %@", flutterEventSink);
    flutterEventSink = events;
//    flutterEventSink(@"hello");
    return nil;
}

- (void)sendEvent:(NSString *)msg{
    if(flutterEventSink){
        flutterEventSink(msg);
    }
}

- (FlutterError *)onCancelWithArguments:(id)arguments{
    return nil;
}


- (void)showReceivedData:(id)result className:(NSString*)className
{
    NSMutableArray *models = [NSMutableArray array];
    Class dataClass = NSClassFromString(className);
    if([result isKindOfClass:[NSArray class]]){
        for (NSDictionary *dic in result) {
            id model = [[dataClass alloc] initWithDictionary:dic];
            [models addObject:model];
        }
    } else if([result isKindOfClass:[NSDictionary class]]){
        id model = [[dataClass alloc] initWithDictionary:result];
        [models addObject:model];
    }
}


///-------------------
- (void)XMTrackPlayerDidEnd{
    [self sendEvent:@"{\"type\":\"player\",\"status\":\"onPlayStop\"}"];
}

- (void)XMTrackPlayerDidPaused{
    [self sendEvent:@"{\"type\":\"player\",\"status\":\"onPlayPause\"}"];
}

- (void)XMTrackPlayerDidPlaying{
    [self sendEvent:@"{\"type\":\"player\",\"status\":\"onPlayStart\"}"];
}

- (void)XMTrackPlayerDidStopped{
    [self sendEvent:@"{\"type\":\"player\",\"status\":\"onPlayStop\"}"];
}

- (void)XMTrackPlayerDidPlaylistEnd{
    
}

- (void)XMTrackPlayerWillPlaying{
    [self sendEvent:@"{\"type\":\"player\",\"status\":\"onPlayStart\"}"];
}

- (void)XMTrackPlayerDidChangeToTrack:(XMTrack *)track{
    NSString *string = [NSString stringWithFormat:@"{\"type\":\"player\",\"status\":\"onSoundSwitch\",\"id\":%ld}", (long)track.trackId];
    [self sendEvent:string];
}

- (void)XMTrackPlayNotifyCacheProcess:(CGFloat)percent{
    
}

- (void)XMTrackPlayerDidReplacePlayList:(NSArray *)list{
    
}

- (void)XMTrackPlayerDidPausePlayForBadNetwork{
    
}

- (void)XMTrackPlayerDidErrorWithType:(NSString *)type withData:(NSDictionary *)data{
    [self sendEvent:@"{\"type\":\"player\",\"status\":\"onError\"}"];
}

- (void)XMTrackPlayNotifyProcess:(CGFloat)percent currentSecond:(NSUInteger)currentSecond{
    NSString *string = [NSString stringWithFormat:@"{\"type\":\"player\",\"status\":\"onPlayProgress_ios\",\"percent\":%f}", percent];
    [self sendEvent:string];
}

- (void)XMTrackPlayerDidFailedToPlayTrack:(XMTrack *)track withError:(NSError *)error{
    [self sendEvent:@"{\"type\":\"player\",\"status\":\"onError\"}"];
}

- (BOOL)XMTrackPlayerShouldContinueNextTrackWhenFailed:(XMTrack *)track{
    return false;
}



@end
